package com.aimusic.service.impl;

import com.aimusic.domain.po.Friendships;

import com.aimusic.domain.po.User;
import com.aimusic.domain.po.UserProfile;
import com.aimusic.domain.vo.FriendVO;
import com.aimusic.mapper.FriendshipsMapper;

import com.aimusic.service.IFriendshipsService;
import com.aimusic.service.IUserProfileService;
import com.aimusic.service.IUserService;
import com.aimusic.utils.CurrentHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 好友关系表（记录用户与好友的关联） 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-09-29
 */
@Service
@RequiredArgsConstructor
public class FriendshipsServiceImpl extends ServiceImpl<FriendshipsMapper, Friendships> implements IFriendshipsService {
    private final IUserProfileService userProfileService;
    private final IUserService userService;
    @Override
    public List<FriendVO> getFriends() {
        // 1. 查询当前用户的所有有效好友关系（状态为1：已确认）
        Integer userId = CurrentHolder.getCurrentId();
        List<Friendships> list = lambdaQuery().eq(Friendships::getUserId, userId)
                                 .eq(Friendships::getStatus, 1).list();
        // 2. 用好友id查询好友信息表
        List<Long> friendIds = list.stream()
                .map(Friendships::getFriendId) // 提取friendId
                .distinct() // 去重，优化查询效率
                .collect(Collectors.toList());

        //获取好友uesr_profile的map集合
        List<UserProfile> friendInfoList = userProfileService.lambdaQuery()
                .in(UserProfile::getUserId, friendIds).list();
        Map<Long, UserProfile> friendMap = friendInfoList.stream()
                .collect(Collectors.toMap(
                        UserProfile::getUserId,  // key：好友ID（User的id）
                        c -> c   // value：好友信息（User对象）
                        // 可选：若有重复ID（理论上不会），用(k1,k2)->k1保留第一个
                ));

        //获取好友user的map集合
        List<User> friendList = userService.lambdaQuery().in(User::getId, friendIds).list();
        Map<Long, User> friendUserMap = friendList.stream()
                .collect(Collectors.toMap(
                        User::getId,  // key：好友ID（User的id）
                        c -> c   // value：好友信息（User对象）
                        // 可选：若有重复ID（理论上不会），用(k1,k2)->k1保留第一个
                ));

        // 2. 遍历好友关系，组装FriendVO
        List<FriendVO> voList=new ArrayList<>();
        for (Friendships friendship : list) {
            FriendVO friendVO = new FriendVO();
            friendVO.setId(friendship.getFriendId());
            friendVO.setNickname(friendMap.get(friendship.getFriendId()).getNickname());
            friendVO.setUsername(friendUserMap.get(friendship.getFriendId()).getUsername());
            friendVO.setAvatar(friendMap.get(friendship.getFriendId()).getAvatar());
            friendVO.setOnlineStatus(friendUserMap.get(friendship.getFriendId()).getOnlineStatus());
            friendVO.setLastActiveTime(friendUserMap.get(friendship.getFriendId()).getLastActiveTime());
            friendVO.setLastMessage("最有一条消息（测试）");
            friendVO.setUnreadCount(1);
            friendVO.setLocation(friendMap.get(friendship.getFriendId()).getLocation());
            friendVO.setBio(friendMap.get(friendship.getFriendId()).getBio());
            friendVO.setJoinTime(friendUserMap.get(friendship.getFriendId()).getCreateTime());
            voList.add(friendVO);
        }


        return voList;
    }
}
